package cn.zqh.minio.service.impl;

import cn.zqh.bean.api.CommonResult;
import cn.zqh.bean.api.ResultCode;
import cn.zqh.bean.bo.*;
import cn.zqh.minio.client.CommodityClient;
import cn.zqh.minio.client.StoreClient;
import cn.zqh.minio.config.BSException;
import cn.zqh.minio.config.SensitiveFilter;
import cn.zqh.minio.holder.LoginUserHolder;
import cn.zqh.minio.mapper.CommentMapper;
import cn.zqh.minio.service.CommentService;
import cn.zqh.uuid.utils.SnowflakeId;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zqh
 * @since 2023-02-21
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Resource
    private CommentMapper commentMapper;

    @Autowired
    private LoginUserHolder loginUserHolder;

    @Autowired
    private CommodityClient commodityClient;

    @Autowired
    private StoreClient storeClient;

    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private SensitiveFilter sensitiveFilter;

    /**
      * @Author: zqh
      * @Date:
      * @Description: 添加一条商品评论
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult creaetACommodityComment(String commodityId, String message) {
        CommonResult forObject = restTemplate.getForObject("http://127.0.0.1:9801/commodity/getfoodsById?id=" + commodityId, CommonResult.class);
        String s = JSON.toJSONString(forObject.getData());
        Commodity commodity = JSON.parseObject(s, Commodity.class);
//        Commodity commodity = commodityClient.getCommodityById(commodityId);
//        System.out.println(commodity);
        if (commodity == null){
            throw new BSException(ResultCode.VALIDATE_FAILED.getCode(),ResultCode.VALIDATE_FAILED.getMessage());
        }
        UserDTO userDTO = loginUserHolder.getCurrentUser();
        Comment comment = new Comment();
        comment.setCommentId("comment"+ SnowflakeId.nextId())
                .setCommentStyle(1)
                .setSorcid(commodityId)
                .setUserId(userDTO.getId())
                //敏感词过滤
                .setCmessage(sensitiveFilter.filter(message))
                .setIsDelete(0);
        int insert = commentMapper.insert(comment);
        if (insert != 1){
            return CommonResult.failed();
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 给店铺添加评论
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult createAStoreComment(String storeId, String message) {
        Store store = storeClient.getStoreInformationByStoreId(storeId);
        if (store == null){
            throw new BSException(ResultCode.VALIDATE_FAILED.getCode(),ResultCode.VALIDATE_FAILED.getMessage());
        }
        UserDTO userDTO = loginUserHolder.getCurrentUser();
        Comment comment = new Comment();
        comment.setCommentId("comment"+ SnowflakeId.nextId())
                .setCommentStyle(2)
                .setSorcid(storeId)
                .setUserId(userDTO.getId())
                .setCmessage(sensitiveFilter.filter(message))
                .setIsDelete(0);
        int insert = commentMapper.insert(comment);
        if (insert != 1){
            return CommonResult.failed();
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 通过id删除某条评论
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult delCommentById(String commentId) {
        int i = commentMapper.deleteById(commentId);
        if (i != 1){
            return CommonResult.failed();
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }
    
    /**
      * @Author: zqh
      * @Date: 
      * @Description: 查询某个店铺的评论
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult getCommentsBySorcid(Integer style,String sorcid, Integer page, Integer size) {
        int x = (page - 1) * size;
        List<Comment> list = commentMapper.getCommentsByPage(style, sorcid, x, size);
        ArrayList<User> users = new ArrayList<>();
        for (Comment comment : list) {
            CommonResult forUser = restTemplate.getForObject("http://127.0.0.1:9501/user/getUserById?userId=" + comment.getUserId(), CommonResult.class);
            String s1 = JSON.toJSONString(forUser.getData());
            User user = JSON.parseObject(s1, User.class);
            users.add(user);
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("comment",list);
        hashMap.put("user",users);
        return CommonResult.success(hashMap);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 查询某个商品评论的数量
    */
    @Override
    public CommonResult getAllCommentNumById(String commodityId) {
        Integer number = commentMapper.getComCommentNumber(commodityId);
        return CommonResult.success(number);
    }


}
